package com.leetcode.sorts.back_track;

import java.util.*;

/**
 * @Author: WuPeng
 * @Date: 2021/6/15 7:55 下午
 * 39.组合总和
 */
public class CombinationSum_39 {

    List<List<Integer>> res = new ArrayList<>();
    Deque<Integer> res_tmp = new LinkedList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracking(candidates, target, 0);
        return res;
    }

    private void backTracking(int[] candidates, int target, int index) {
        if (sum > target) return;
        if (sum == target){
            res.add(new ArrayList<>(res_tmp));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            sum += candidates[i];
            res_tmp.offer(candidates[i]);
            backTracking(candidates, target, i);
            res_tmp.pollLast();
            sum -= candidates[i];
        }
    }

    public static void main(String[] args) {
        int[] candidates = {2,3,6,7};

        CombinationSum_39 com = new CombinationSum_39();
        List<List<Integer>> list = com.combinationSum(candidates, 7);
        System.out.println(Arrays.toString(list.toArray()));
    }

}
